<template>
  <div class="chat-container">
    <div class="chat-box" ref="chatBox">
      <div v-for="(item, index) in chatHistory" :key="index" class="chat-item">
        <div class="chat-user" v-if="item.type === 'user'">
          <strong>你：</strong> {{ item.message }}
        </div>
        <div class="chat-agent" v-else>
          <strong>小西：</strong>
          <VueMarkdown :source="item.message" />
        </div>
      </div>
    </div>
    <div class="input-area">
      <input
        v-model="userInput"
        @keydown.enter="handleEnter"
        @confirm="handleEnter"
        placeholder="请输入对话内容"
        ref="inputRef"
        confirm-type="send"
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script lang="ts">
import axios from 'axios'
import { ref, defineComponent, nextTick, watch } from 'vue'
import VueMarkdown from 'vue3-markdown-it'

interface ChatItem {
  type: 'user' | 'agent';
  message: string;
  _debug?: any;
}

export default defineComponent({
  name: 'Chat',
  components: {
    VueMarkdown
  },
  emits: ['history-updated'],
  setup(props, { emit }) {
    const userInput = ref<string>('')
    const chatHistory = ref<ChatItem[]>([])
    const sessionId = ref<string>('')
    const chatBox = ref<HTMLElement | null>(null)
    const inputRef = ref<HTMLInputElement | null>(null)

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (chatBox.value) {
          chatBox.value.scrollTop = chatBox.value.scrollHeight
        }
      })
    }

    // 监听 chatHistory 变化并发射事件
    watch(chatHistory, (newVal) => {
      console.log('[Debug] chatHistory updated:', newVal.length)
      emit('history-updated', newVal.length)
      scrollToBottom()
    }, { deep: true })

    // 处理回车键或确认事件
    const handleEnter = (event: KeyboardEvent | Event) => {
      console.log('[Debug] handleEnter triggered, event type:', event.type)
      if (event instanceof KeyboardEvent && event.shiftKey) {
        // Shift + Enter 换行
        console.log('[Debug] Shift + Enter, allowing newline')
        return
      }
      event.preventDefault()
      sendMessage()
    }

    const sendMessage = async () => {
      const trimmedInput = userInput.value.trim()
      if (!trimmedInput) {
        console.log('[Debug] Empty input, focusing')
        inputRef.value?.focus()
        return
      }

      const requestId = Date.now().toString(36) + Math.random().toString(36).substr(2)
      console.debug(`[Request ${requestId}] 发送请求`, {
        input: trimmedInput,
        sessionId: sessionId.value
      })

      chatHistory.value.push({ type: 'user', message: trimmedInput })
      userInput.value = ''
      inputRef.value?.focus()

      try {
        const response = await axios.post(
          'http://localhost:5000/chat',
          {
            input: trimmedInput,
            sessionId: sessionId.value
          },
          {
            timeout: 10000000000,
            headers: {
              'X-Request-ID': requestId,
              'Debug-Mode': process.env.NODE_ENV === 'development'
            }
          }
        )

        console.debug(`[Response ${requestId}] 原始响应`, response)

        if (response.data?.code === 0) {
          console.info('成功响应:', response.data)
          chatHistory.value.push({
            type: 'agent',
            message: response.data.response,
            _debug: process.env.NODE_ENV === 'development' ? response.data : null
          })
          sessionId.value = response.data.sessionId
        } else {
          const errorMsg = response.data?.msg || '未知错误'
          console.error('业务逻辑错误:', errorMsg, response.data)
          chatHistory.value.push({
            type: 'agent',
            message: `服务异常：${errorMsg} (错误码: ${response.data?.code || '未知'})`,
            _debug: process.env.NODE_ENV === 'development' ? response.data : null
          })
        }
      } catch (error: unknown) {
        console.error('请求失败:', error)
        const errorDetails = {
          message: (error as any).message || '未知错误',
          code: (error as any).response?.status || 'NETWORK_ERROR',
          data: (error as any).response?.data || null
        }

        chatHistory.value.push({
          type: 'agent',
          message: `请求失败：${errorDetails.message}`,
          _debug: process.env.NODE_ENV === 'development' ? errorDetails : null
        })
      } finally {
        console.debug(`[Request ${requestId}] 请求处理完成`)
      }
    }

    return { userInput, chatHistory, sendMessage, chatBox, inputRef, handleEnter }
  }
})
</script>

<style scoped>
.chat-container {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-family: '宋体', Helvetica, Arial, sans-serif; /* 添加统一字体 */
  font-size: 25px; /* 添加统一字体大小 */
  position: relative;
}

.chat-box {
  border: 1px solid #ccc;
  padding: 10px;
  min-height: 200px;
  max-height: 600px;
  overflow-y: auto;
  margin-bottom: 10px;
}

.chat-item {
  margin-bottom: 10px;
}

.chat-user {
  text-align: right;
  color: #333;
}

.chat-agent {
  text-align: left;
  color: #0a2aff;
}

.input-area {
  display: flex;
  gap: 10px;
}

input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  background-color: #007bff;
  border: none;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.markdown-body {
  font-size: 14px;
  line-height: 1.6;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  margin: 10px 0;
}

.markdown-body p {
  margin: 5px 0;
}

.markdown-body ul,
.markdown-body ol {
  padding-left: 20px;
}

.markdown-body code {
  background-color: #f5f5f5;
  padding: 2px 4px;
  border-radius: 4px;
}

.markdown-body pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

/* 固定输入栏 */
.chat-container {
  position: relative;
}

.chat-box {
  margin-bottom: 60px;
}

.input-area {
  position: absolute;
  bottom: 10px;
  left: 20px;
  right: 20px;
}
</style>